package com.seo.service.keyword.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.seo.mapper.keyword.NewStationMapper;
import com.seo.mapper.user.ConfigMapper;
import com.seo.pojo.KeyWord;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.NewStationService;
import com.seo.service.user.sdk.UserService;
import com.seo.utils.CommonUtil;
import com.seo.utils.DateUtil;
import com.seo.utils.KeyWordsIndex;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("newStationService")
public class NewStationServiceImpl implements NewStationService {

	@Autowired
	private NewStationMapper newStationMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private ConfigMapper configMapper;

	@Value("${keyword.key}")
	private String key;
	@Value("${keyword.shenma.url}")
	private String shenmaUrl;
	@Value("${keyword.so.url}")
	private String soUrl;
	@Value("${keyword.sougou.url}")
	private String sougouUrl;
	@Value("${keyword.baidu.url}")
	private String baiduUrl;

	@Override
	public List<Map<String, Object>> getNewDomainList(Map<String, Object> param) {
		return newStationMapper.getNewDomainList(param);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ReturnBody saveNewKeywordsDomain(Map<String, Object> params) {
		log.info("admin添加网站开始--- param={}", params);
		ReturnBody rb = ReturnBody.init();
		String userName = params.get("userName") + "";
		ReturnBody userByName = userService.getUserByName(userName);
		if (!userByName.isSuccess()) {
			return rb.rollback("用户不存在");
		}
		Map<String, Object> user = (Map<String, Object>) userByName.get("user");
		String parentId = user.get("parentId") + "";
		if (!"0".equals(parentId)) {
			return rb.rollback("该用户不是本账号下级用户");
		}
		params.put("userId", user.get("id"));
		int num = newStationMapper.getNewDomainNum(params);
		if (num > 0) {
			return rb.error("该网站已存在");
		}
		String domain = params.get("domain") + "";
		rb = CommonUtil.isUrlGroup(domain);
		if (!rb.isSuccess()) {
			rb.error("域名格式有误！");
			return rb;
		}
		List<Map<String, Object>> userParent = getUserParent(user);
		if (userParent == null || userParent.isEmpty()) {
			return rb.error("未查找到用户");
		}
		try {
			params.put("state", "01");
			params.put("realUserId", user.get("id"));
			newStationMapper.saveNewKeywordsDomain(params);
			int x = 0;
			String relationId = "";
			for (Map<String, Object> map : userParent) {
				Map<String, Object> pam = new HashMap<String, Object>();
				pam.put("domain_id", params.get("domainId"));
				pam.put("parent_id", map.get("parent_id"));
				pam.put("user_id", map.get("id"));
				pam.put("create_id", params.get("create_id"));
				newStationMapper.saveNewKeywordsDomainRelation(pam);
				if (x != 0) {
					pam.put("relationId", relationId);
					// 修改网站关联表下级用户
					newStationMapper.updateNewKeyWordDomainRelationToChildUserId(pam);
					relationId = pam.get("id") + "";
				} else {
					relationId = pam.get("id") + "";
				}
				x++;
			}
			rb.success();
			log.info("admin添加网站结束");
		} catch (Exception e) {
			rb.rollback("添加失败");
			e.printStackTrace();
		} finally {
			rb.result();
		}
		return rb;
	}

	public List<Map<String, Object>> getUserParent(Map<String, Object> user) {
		List<Map<String, Object>> userRelation = userService.getUserParent(user);
		return userRelation;
	}

	@Override
	public ReturnBody updateNewKeywordsDomain(Map<String, Object> params) {
		log.info("admin编辑网站开始--- param={}", params);
		ReturnBody rb = ReturnBody.init();
		try {
			String domain = params.get("domain") + "";
			rb = CommonUtil.isUrlGroup(domain);
			if (!rb.isSuccess()) {
				rb.error("域名格式有误！");
				return rb;
			}
			int num = newStationMapper.updateNewKeywordsDomain(params);
			if (num == 0) {
				return rb.rollback();
			}
			newStationMapper.updateNewKeywordsVenderIdByDomainId(params);
			rb.success();
		} catch (Exception e) {
			rb.rollback("修改失败");
			e.printStackTrace();
		} finally {
			rb.result();
		}

		return rb;
	}

	@Override
	public ReturnBody updateDomainState(Map<String, Object> param) {
		ReturnBody rb = ReturnBody.init();
		int num = newStationMapper.updateDomainState(param);
		rb = num == 0 ? rb.error("修改失败") : rb.success();
		return rb;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ReturnBody saveDomainKeyWordToAdmin(Map<String, Object> param, String serviceType) {
		ReturnBody rb = ReturnBody.init();
		String userName = param.get("userName") + "";
		String keyWord = param.get("keyWord") + "";
		String domain = param.get("domain") + "";
		String createId = param.get("createId") + "";
		String engineCode = param.get("engineCode") + "";
		String domainId = param.get("domainId") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(keyWord) || StringUtils.isEmpty(domain) || StringUtils.isEmpty(domainId)
				|| StringUtils.isEmpty(createId) || StringUtils.isEmpty(engineCode)) {

			return rb.rollback("参数不能为空");
		}
		ReturnBody userByName = userService.getUserByName(userName);
		if (!userByName.isSuccess()) {
			return rb.rollback("用户不存在");
		}
		Map<String, Object> user = (Map<String, Object>) userByName.get("user");
		String parentIds = user.get("parentId") + "";
		if (!"0".equals(parentIds)) {
			return rb.rollback("此用户不是本账号下级用户");
		}
		param.put("user", user);
		Integer userId = newStationMapper.getUserIdByDomain(domain);
		user.put("id", userId);
		try {
			rb.run(CommonUtil.isUrlGroup(domain));

			if (!rb.isSuccess()) {
				rb.getResult().setIsRollBack("01");
				return rb;
			}
			rb.run(CommonUtil.isKeywordGroup(keyWord, "\n"));
			if (!rb.isSuccess()) {
				rb.getResult().setIsRollBack("01");
				return rb;
			}
			String[] engineCodes = engineCode.split(",");
			List<String> keyWords = rb.getCollection("keywordList", String.class);
			// 获取用户子父信息
			log.info("获取用户子父信息开始--- userId={}", user.get("id"));
			List<Map<String, Object>> userParent = getUserParent(user);
			if (userParent == null || userParent.size() == 0) {
				return rb.rollback("用户不存在");
			}
			log.info("获取用户子父信息结束--- userRelation={}", userParent);
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int y = 0; y < keyWords.size(); y++) {
					String kw = keyWords.get(y).trim();
					// 封装关键词字段
					Map<String, Object> pa = new HashMap<>();
					pa.put("userId", userParent.get(0).get("id"));
					pa.put("realUserId", userParent.get(userParent.size() - 1).get("id"));
					pa.put("keyWord", kw);
					pa.put("engineCode", engineCodes[i]);
					pa.put("engineCodes", getEngineCode(engineCodes[i]));
					pa.put("domain", domain);
					pa.put("createId", createId);
					pa.put("domainId", domainId);
					//pa.put("venderId", newStationMapper.getVenderIdByName(param));
					pa.put("state", "01");
					int count = newStationMapper.getDomainKeyWordNum(pa);
					if (count > 0) {
						failList.add(pa);
						continue;
					}
					String index = KeyWordsIndex.getKeyWordsInde(kw, key, engineCodes[i]);
					pa.put("keywordIndex", index);
					pa.put("initRanking", KeyWordsIndex.getKeyWordsRanking(kw, domain, engineCodes[i]).get("ranking"));
					pa.put("domainType", "http://");
					Map<String, Object> vipLevel = null;
					// 获取顶级用户信息
					Map<String, Object> ma = userParent.get(0);
					String state = "";
					String price = "";
					if (ma != null) {
						int msg = getUserState(ma,user);
						if (msg == 0) {
							return rb.rollback("添加失败，余额过低或用户异常");
						}
						String price2 = ma.get("price2") + "";
						if (!"null".equals(price2) && !"".equals(price2) && !"0.0000".equals(price2)) {
							price = price2;
						} else {

							String roleCode = ma.get("roleCode") + "";
							if ("proxy".equals(roleCode) || "02".equals(roleCode)) {
								ma.put("roleCode", "02");
							} else {
								ma.put("roleCode", "01");
							}
							ma.put("serviceType", serviceType);
							// 获取顶级用户价格信息
							ma.put("types", "xz");
							String parentId = ma.get("parent_id") + "";
							if ("0".equals(parentId)) {
								vipLevel = userService.getPriceToVipLevel(ma);
							} else {
								ma.put("superId", parentId);
								vipLevel = userService.getUserPriceToVipLevel(ma);
							}
							if (vipLevel == null || vipLevel.isEmpty()) {
								return rb.rollback("未查找到用户价格");
							}
							state = (String) vipLevel.get("state");
							if (!"01".equals(state)) {
								return rb.rollback("用户等级价格未启用");
							}
							String init_price = vipLevel.get("init_price") + "";
							if ("0.0000".equals(init_price) || "0".equals(init_price) || "".equals(init_price)
									|| init_price == null) {
								return rb.rollback("用户等级价格未设置");
							}
							price = getPriceMethod(vipLevel, index);
						}
					}

					pa.put("price", price);
					// 添加关键词
					newStationMapper.saveNewDomainKeyWord(pa);
					successList.add(pa);

					int x = 0;
					String relationId = "";
					// 添加关键词关联表
					for (Map<String, Object> map : userParent) {
						Map<String, Object> m = new HashMap<>();
						Map<String, Object> pvl = null;
						if (map != null) {
							int msg = getUserState(map,user);
							if (msg == 0) {
								return rb.rollback("添加失败，余额过低或用户异常");
							}
							String price1 = map.get("price1") + "";
							if (!"null".equals(price1) && !"".equals(price1) && !"0.0000".equals(price1)) {
								price = price1;
							} else {
								String roleCode = map.get("roleCode") + "";
								if ("proxy".equals(roleCode) || "02".equals(roleCode)) {
									map.put("roleCode", "02");
								} else {
									map.put("roleCode", "01");
								}
								map.put("serviceType", serviceType);
								map.put("types", "xz");
								String parentId = map.get("parent_id") + "";
								if ("0".equals(parentId)) {
									pvl = userService.getPriceToVipLevel(map);
								} else {
									map.put("superId", parentId);
									pvl = userService.getUserPriceToVipLevel(map);
								}
								if (pvl == null || pvl.isEmpty()) {
									return rb.rollback("未查找到用户价格");
								}
								state = (String) pvl.get("state");
								if (!"01".equals(state)) {
									return rb.rollback("用户等级价格未启用");
								}
								String init_price = pvl.get("init_price") + "";
								if ("0.0000".equals(init_price) || "0".equals(init_price) || "".equals(init_price)
										|| init_price == null) {
									return rb.rollback("用户等级价格未设置");
								}
								price = getPriceMethod(pvl, index);
							}
						}
						m.put("keywords_id", pa.get("id"));
						m.put("parentId", map.get("parent_id"));
						m.put("userId", map.get("id"));
						m.put("price", price);
						m.put("create_id", createId);
						m.put("domainId", domainId);
						// 添加关键词价格关联表
						newStationMapper.saveDomainKeyWordRelation(m);
						if (x != 0) {
							m.put("relationId", relationId);
							// 修改关键词关联表下级用户
							newStationMapper.updateDomainKeyWordRelationToChildUserId(m);
							relationId = m.get("id") + "";
						} else {
							relationId = m.get("id") + "";
						}
						x++;
					}
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			rb.rollback("添加失败");
			e.printStackTrace();
		} finally {
			rb.result();
		}
		return rb.success();
	}

	public String getEngineCode(String engineCodes) {
		if ("01".equals(engineCodes)) {
			engineCodes = "百度PC";
		}
		if ("02".equals(engineCodes)) {
			engineCodes = "百度移动";
		}
		if ("03".equals(engineCodes)) {
			engineCodes = "360PC";
		}
		if ("04".equals(engineCodes)) {
			engineCodes = "360移动";
		}
		if ("05".equals(engineCodes)) {
			engineCodes = "神马";
		}
		if ("06".equals(engineCodes)) {
			engineCodes = "搜狗pc";
		}
		if ("07".equals(engineCodes)) {
			engineCodes = "搜狗移动";
		}
		return engineCodes;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ReturnBody saveNewKeywordsDomainCustomer(Map<String, Object> params) {
		log.info("添加网站开始--- param={}", params);
		ReturnBody rb = ReturnBody.init();
		String userName = params.get("userName") + "";
		Map<String, Object> user = (Map<String, Object>) params.get("user");
		if (user == null || user.isEmpty()) {
			return rb.rollback("用户不存在");
		}
		int userId = (Integer) user.get("id");
		if (!StringUtils.isEmpty(userName)) {
			ReturnBody userByName = userService.getUserByName(userName);
			if (!userByName.isSuccess()) {
				return rb.rollback("用户不存在");
			}
			user = (Map<String, Object>) userByName.get("user");
			int parentId = (Integer) user.get("parentId");
			if (parentId != userId) {
				return rb.rollback("该用户不是本账号下级用户");
			}
		}
		params.put("userId", user.get("id"));
		// 查看网站是否存在
		int num = newStationMapper.getNewDomainNum(params);
		if (num > 0) {
			return rb.error("该网站已存在");
		}
		String domain = params.get("domain") + "";
		rb = CommonUtil.isUrlGroup(domain);
		if (!rb.isSuccess()) {
			return rb.error("域名格式有误！");
		}
		List<Map<String, Object>> userParent = getUserParent(user);
		if (userParent == null || userParent.isEmpty()) {
			return rb.error("未查找到用户");
		}
		try {
			params.put("userId", userParent.get(0).get("id"));
			params.put("realUserId", userParent.get(userParent.size() - 1).get("id"));
			params.put("create_id", 0);
			params.put("state", "01");
			newStationMapper.saveNewKeywordsDomain(params);
			String quota = configMapper.getConfig("newStation_min_quota");
			int x = 0;
			String relationId = "";
			for (Map<String, Object> map : userParent) {
				
				BigDecimal balance = (BigDecimal) map.get("balance");
				BigDecimal minQuota = new BigDecimal(quota);
				
				if (balance == null || minQuota == null || balance.compareTo(minQuota) == -1) {
					return rb.rollback("保存失败,用户余额不足");
				}
				Map<String, Object> pam = new HashMap<String, Object>();
				pam.put("domain_id", params.get("domainId"));
				pam.put("parent_id", map.get("parent_id"));
				pam.put("user_id", map.get("id"));
				pam.put("create_id", params.get("create_id"));
				newStationMapper.saveNewKeywordsDomainRelation(pam);
				if (x != 0) {
					pam.put("relationId", relationId);
					// 修改网站关联表下级用户
					newStationMapper.updateNewKeyWordDomainRelationToChildUserId(pam);
					relationId = pam.get("id") + "";
				} else {
					relationId = pam.get("id") + "";
				}
				x++;
			}
			rb.success();
			log.info("添加网站结束");
		} catch (Exception e) {
			rb.rollback("添加失败");
			e.printStackTrace();
		} finally {
			rb.result();
		}
		return rb;
	}

	private int getUserState(Map<String, Object> ma,Map<String, Object> user) {
		int num = 0;
		Integer uid = (Integer) user.get("id");
		Integer id = (Integer) ma.get("id");
		String state = (String) ma.get("state");
		String isDelete = (String) ma.get("isDelete");
		BigDecimal balance = (BigDecimal) ma.get("balance");
		String quota = configMapper.getConfig("min_quota");
		BigDecimal minQuota = new BigDecimal(quota);
		if ("02".equals(state) || "01".equals(isDelete)) {
			return num;
		}
	/*	if(uid != id) {
			if (balance == null || minQuota == null) {
				return num;
			}
			if(balance.compareTo(minQuota) == -1) {
				return num;
			}
		}*/
		num = 1;
		return num;
	}

	public String getPriceMethod(Map<String, Object> vipLevel, String index) {
		BigDecimal price = null;
		// 原始价格
		BigDecimal init_price = (BigDecimal) vipLevel.get("init_price");
		// 指数递增价格
		BigDecimal add_price = (BigDecimal) vipLevel.get("add_price");
		// 递增指数
		Integer add_index = (Integer) vipLevel.get("add_index");
		// 关键词指数
		Integer indexs = Integer.parseInt(index);
		if (indexs == -1) {
			indexs = 0;
		}
		if (add_index == 0) {
			return init_price + "";
		}
		Integer indexUnit = 0;
		if (indexs > add_index) {
			indexUnit = indexs / add_index;
			Integer remainder = indexs % add_index;
			if (remainder > 0) {
				indexUnit = indexUnit + 1;
			}
		}
		BigDecimal addi = new BigDecimal(indexUnit.toString());
		BigDecimal price1 = addi.multiply(add_price);
		price = price1.add(init_price);
		return price + "";
	}

	@SuppressWarnings("unchecked")
	@Override
	public ReturnBody saveDomainKeyWordToCustomer(Map<String, Object> param) {
		ReturnBody rb = ReturnBody.init();
		String serviceType = "02";
		String userName = param.get("userName") + "";
		String keyWord = param.get("keyWord") + "";
		String domain = param.get("domain") + "";
		String createId = param.get("createId") + "";
		String engineCode = param.get("engineCode") + "";
		String domainId = param.get("domainId") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(keyWord) || StringUtils.isEmpty(domain) || StringUtils.isEmpty(domainId)
				|| StringUtils.isEmpty(createId) || StringUtils.isEmpty(engineCode)) {

			return rb.rollback("参数不能为空");
		}
		ReturnBody userByName = userService.getUserByName(userName);
		if (!userByName.isSuccess()) {
			return rb.rollback("用户不存在");
		} 
		Map<String, Object> user = (Map<String, Object>) userByName.get("user");
		
		param.put("user", user);
		try {
			rb.run(CommonUtil.isUrlGroup(domain));

			if (!rb.isSuccess()) {
				rb.getResult().setIsRollBack("01");
				return rb;
			}
			rb.run(CommonUtil.isKeywordGroup(keyWord, "\n"));
			if (!rb.isSuccess()) {
				rb.getResult().setIsRollBack("01");
				return rb;
			}
			String[] engineCodes = engineCode.split(",");
			List<String> keyWords = rb.getCollection("keywordList", String.class);
			// 获取用户子父信息
			log.info("获取用户子父信息开始--- userId={}", user.get("id"));
			List<Map<String, Object>> userParent = getUserParent(user);
			if (userParent == null || userParent.size() == 0) {
				return rb.rollback("用户不存在");
			}
			log.info("获取用户子父信息结束--- userRelation={}", userParent);
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int y = 0; y < keyWords.size(); y++) {
					String kw = keyWords.get(y).trim();
					// 封装关键词字段
					Map<String, Object> pa = new HashMap<>();
					pa.put("userId", userParent.get(0).get("id"));
					pa.put("realUserId", userParent.get(userParent.size() - 1).get("id"));
					pa.put("keyWord", kw);
					pa.put("engineCode", engineCodes[i]);
					pa.put("engineCodes", getEngineCode(engineCodes[i]));
					pa.put("domain", domain);
					//pa.put("venderId", newStationMapper.getVenderIdByName(param));
					pa.put("domainId", domainId);
					pa.put("createId", createId);
					pa.put("state", "01");
					int count = newStationMapper.getDomainKeyWordNum(pa);
					if (count > 0) {
						failList.add(pa);
						continue;
					}
					String index = KeyWordsIndex.getKeyWordsInde(kw, key, engineCodes[i]);
					pa.put("keywordIndex", index);
					pa.put("initRanking", KeyWordsIndex.getKeyWordsRanking(kw, domain, engineCodes[i]).get("ranking"));
					pa.put("domainType", "http://");
					Map<String, Object> vipLevel = null;
					// 获取顶级用户信息
					Map<String, Object> ma = userParent.get(0);
					String state = "";
					String price = "";
					if (ma != null) {
						int msg = getUserState(ma,user);
						if (msg == 0) {
							return rb.rollback("添加失败，余额过低或用户异常");
						}
						String price2 = ma.get("price2") + "";
						if (!"null".equals(price2) && !"".equals(price2) && !"0.0000".equals(price2)) {
							price = price2;
						} else {

							String roleCode = ma.get("roleCode") + "";
							if ("proxy".equals(roleCode) || "02".equals(roleCode)) {
								ma.put("roleCode", "02");
							} else {
								ma.put("roleCode", "01");
							}
							ma.put("serviceType", serviceType);
							// 获取顶级用户价格信息
							String parentId = ma.get("parent_id") + "";
							ma.put("types", "xz");
							if ("0".equals(parentId)) {
								vipLevel = userService.getPriceToVipLevel(ma);
							} else {
								ma.put("superId", parentId);
								vipLevel = userService.getUserPriceToVipLevel(ma);
							}
							if (vipLevel == null || vipLevel.isEmpty()) {
								return rb.rollback("未查找到用户价格");
							}
							state = (String) vipLevel.get("state");
							if (!"01".equals(state)) {
								return rb.rollback("用户等级价格未启用");
							}
							String init_price = vipLevel.get("init_price") + "";
							if ("0.0000".equals(init_price) || "0".equals(init_price) || "".equals(init_price)
									|| init_price == null) {
								return rb.rollback("用户等级价格未设置");
							}
							price = getPriceMethod(vipLevel, index);
						}
					}

					pa.put("price", price);
					// 添加关键词
					newStationMapper.saveNewDomainKeyWord(pa);
					successList.add(pa);

					int x = 0;
					String relationId = "";
					// 添加关键词关联表
					for (Map<String, Object> map : userParent) {
						Map<String, Object> m = new HashMap<>();
						Map<String, Object> pvl = null;
						if (map != null) {
							int msg = getUserState(map,user);
							if (msg == 0) {
								return rb.rollback("添加失败，余额过低或用户异常");
							}
							String price1 = map.get("price1") + "";
							if (!"null".equals(price1) && !"".equals(price1) && !"0.0000".equals(price1)) {
								price = price1;
							} else {
								String roleCode = map.get("roleCode") + "";
								if ("proxy".equals(roleCode) || "02".equals(roleCode)) {
									map.put("roleCode", "02");
								} else {
									map.put("roleCode", "01");
								}
								map.put("serviceType", serviceType);
								map.put("types", "xz");
								String parentId = map.get("parent_id") + "";
								if ("0".equals(parentId)) {
									pvl = userService.getPriceToVipLevel(map);
								} else {
									map.put("superId", parentId);
									pvl = userService.getUserPriceToVipLevel(map);
								}
								if (pvl == null || pvl.isEmpty()) {
									return rb.rollback("未查找到用户价格");
								}
								state = (String) pvl.get("state");
								if (!"01".equals(state)) {
									return rb.rollback("用户等级价格未启用");
								}
								String init_price = pvl.get("init_price") + "";
								if ("0.0000".equals(init_price) || "0".equals(init_price) || "".equals(init_price)
										|| init_price == null) {
									return rb.rollback("用户等级价格未设置");
								}
								price = getPriceMethod(pvl, index);
							}
						}
						m.put("keywords_id", pa.get("id"));
						m.put("parentId", map.get("parent_id"));
						m.put("userId", map.get("id"));
						m.put("price", price);
						m.put("create_id", createId);
						m.put("domainId", domainId);
						// 添加关键词价格关联表
						newStationMapper.saveDomainKeyWordRelation(m);
						if (x != 0) {
							m.put("relationId", relationId);
							// 修改关键词关联表下级用户
							newStationMapper.updateDomainKeyWordRelationToChildUserId(m);
							relationId = m.get("id") + "";
						} else {
							relationId = m.get("id") + "";
						}
						x++;
					}
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			rb.rollback("添加失败");
			e.printStackTrace();
		} finally {
			rb.result();
		}
		return rb.success();
	}

	/**
	 * 关键词列表
	 */
	public List<Map<String, Object>> getKeyWordsList(Map<String, Object> pam) {
		log.info("进入关键词列表service：");
		List<Map<String, Object>> keyWordsList = newStationMapper.getKeyWordsList(pam);
		log.info("关键词列表查询数据：" + keyWordsList);
		return keyWordsList;
	}

	/**
	 * 根据用户id查询此用户所有分组
	 * 
	 * @param pam
	 * @return
	 */
	public List<Map<String, Object>> getGroupByUserId(Integer userId) {
		return newStationMapper.getGroupByUserId(userId);
	}

	/**
	 * 修改价格和类型
	 */
	public ReturnBody updatePriceAndTargetRanking(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = newStationMapper.updatePriceAndTargetRanking(pam);
			if (num == 0) {
				return rb.rollback();
			}
			num = newStationMapper.updateChildPrice(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 修改价格和类型
	 */
	public ReturnBody updateChaildPrice(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = newStationMapper.updateProxyPrice(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 删除
	 */
	public void deleteArr(Map<String, Object> pam) {
		newStationMapper.deleteArr(pam);
	}

	/**
	 * 关键词启用停用
	 */
	public void updatekeyWordReviewDisabled(Map<String, Object> pam) {
		try {
			newStationMapper.updatekeyWordReviewDisabled(pam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批量修改厂商
	 */
	public ReturnBody updateVender(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = newStationMapper.updateVender(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	/**
	 * 导出
	 */
	public XSSFWorkbook exportKeyWord(@RequestParam Map<String, Object> pam, HttpServletResponse response)
			throws Exception {
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			XSSFSheet sheet = workbook.createSheet("信息表");
			List<Map<String, Object>> engineList = newStationMapper.getEngineList(); // 搜索引擎配置
			List<Map<String, Object>> keyWordExportList = newStationMapper.getExprotKeyWordList(pam); // 导出数据
			String fileName = "关键词列表-" + DateUtil.getDay() + ".xlsx";// 设置要导出的文件的名字
			// 新增数据行，并且设置单元格数据

			int rowNum = 1;
			String[] headers = { "关键词", "域名", "搜索引擎", "当前排名", "使用状态" };
			// headers表示excel表中第一行的表头

			XSSFRow row = sheet.createRow(0);
			// 在excel表中添加表头

			for (int i = 0; i < headers.length; i++) {
				XSSFCell cell = row.createCell(i);
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			Map<String, Object> keyWordExportMap = null;
			// 在表中存放查询到的数据放入对应的列
			for (int i = 0; i < keyWordExportList.size(); i++) {
				XSSFRow row1 = sheet.createRow(rowNum);
				keyWordExportMap = keyWordExportList.get(i);
				String domainType = (String) keyWordExportMap.get("domain_type");
				String domain = domainType + (String) keyWordExportMap.get("domain");
				String engineCode = (String) keyWordExportMap.get("engineCode");
				String engineStr = null;
				for (int j = 0; j < engineList.size(); j++) {
					Map<String, Object> engineMap = engineList.get(j);
					String code = (String) engineMap.get("code");
					if (code.equals(engineCode)) {
						engineStr = (String) engineMap.get("name");// 搜索引擎
						break;
					}
				}
				String state = (String) keyWordExportMap.get("state");
				String stateStr = null;
				if ("02".equals(state)) {
					stateStr = "已停用";
				} else if ("00".equals(state)) {
					stateStr = "待审核";
				} else {
					stateStr = "使用中";
				}
				row1.createCell(0).setCellValue(keyWordExportMap.get("keyWordName").toString());
				row1.createCell(1).setCellValue(domain);
				row1.createCell(2).setCellValue(engineStr);
				row1.createCell(3).setCellValue(keyWordExportMap.get("newRanking").toString());
				row1.createCell(4).setCellValue(stateStr);
				rowNum++;
			}
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return workbook;
	}

	/**
	 * 获取厂商
	 */
	public List<Map<String, Object>> getVenderList() {
		return newStationMapper.getVenderList();
	}

	/**
	 * 获取手机引擎
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getEngineList() {
		return newStationMapper.getEngineList();
	}

	/**
	 * 代理关键词列表
	 */
	public List<Map<String, Object>> getKeyWordsEList(Map<String, Object> pam) {
		log.info("进入关键词列表service：");
		List<Map<String, Object>> keyWordsList = newStationMapper.getKeyWordsEList(pam);
		log.info("关键词列表查询数据：" + keyWordsList);
		return keyWordsList;
	}

	/**
	 * 分组
	 */
	public ReturnBody updateGroupById(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			int num = newStationMapper.updateGroupById(pam);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 导入
	 */
	@Transactional
	public ReturnBody importKeyWord(String fileName, MultipartFile file, String importTime) throws Exception {
		ReturnBody rb = ReturnBody.init();
		try {
			long a = System.currentTimeMillis();
			log.info("校验excel格式、版本");
			if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
				log.error("上传文件格式不正确");
			}
			boolean isExcel2003 = true;
			if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
				isExcel2003 = false;
			}
			InputStream is = file.getInputStream();
			Workbook wb = null;
			if (isExcel2003) {
				wb = new HSSFWorkbook(is);
			} else {
				wb = new XSSFWorkbook(is);
			}
			Sheet sheet = wb.getSheetAt(0);
			/********************* 获取excel的头部 ****************************************/
			log.info("校验excel头部");
			String title = checkTitle(sheet); // 返回结果 00 代表没有识别到规定的excel 01
												// 厂商导入excel 02 搜索引擎排名excel
			if ("01".equals(title)) { // 01 厂商导入
				rb = venderImport(sheet);
			} else if ("02".equals(title)) { // 02 搜索引擎排名导入
				rb = engineImport(sheet);
			}
			log.info("\r<br>读excl耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 ");
			if (!rb.isSuccess()) {
				rb.put("msg", "导入失败");
				return rb;
			}
			rb = importDataToDataBase(rb, importTime);
			return rb;
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	/**
	 * 导入插入数据
	 * 
	 */
	public ReturnBody importDataToDataBase(ReturnBody rb, String importTime) {
		List<String> keyWordError = new ArrayList<String>();
		List<KeyWord> keyWordSucessList = rb.getCollection("keyWordSucessList", KeyWord.class);
		Map<String, Object> pam = new HashMap<>();
		StringBuffer errorBu = new StringBuffer();
		long b = System.currentTimeMillis();
		int errNum = 0;
		// 开始把数据插入到数据库中
		for (int i = 0; i < keyWordSucessList.size(); i++) {
			try {
				if (errorBu.length() > 0) {
					errorBu.delete(0, errorBu.length() - 1);
				}
				KeyWord keyWord = keyWordSucessList.get(i);
				String keyWordName = keyWord.getName(); // 关键词
				String domain = keyWord.getDomain(); // 域名
				String engineCode = keyWord.getEngineCode(); // 引擎
				pam.clear();
				pam.put("keyWordName", keyWordName);
				pam.put("domain", domain);
				pam.put("engineCode", engineCode);
				// 根据关键词，域名和引擎查询 主表详情数据
				Map<String, Object> keyWordInfo = newStationMapper.getInfoByDomainAndKeyword(pam);
				/*
				 * 第一次判断：主表 根据域名和关键词查询数据 如果 有值 就更新数据 否则 跳过 第二次判断： 在更新数据之前 根据前台页面传过来的time 时间
				 * 和主表中的 run_time时间做比较 主表 如果 time>=run_time 则更新数据 否则 跳过
				 * 
				 * 明细表落地数据 的前提是 导入的数据 主表中必须存在 否则 不进行落地 首先 根据关键词主表id和run_time作为条件
				 * （run_time等于前台页面穿的time） 查询明细表 是否有值 如果有值 进行修改 没有值 进行添加 在修改之前 根据前台传过来的time 和
				 * 明细表中的 run_time时间进行比较
				 * 
				 * 代理表数据更新的前提是 导入的数据主表中必须存在 否则 不进行更新 根据主表的id 查询代理表 是否有这条数据 有就更新 代理表 没有 跳过
				 * 
				 */
				if (keyWordInfo != null) { // 根据域名和关键词查询数据 如果 有值 就更新数据 否则 跳过
					Long keyWordId = (Long) keyWordInfo.get("id");
					String runTime = (String) keyWordInfo.get("run_time");
					int initRanking = (int) keyWordInfo.get("init_ranking");
					int targetRanking = (int) keyWordInfo.get("target_ranking"); // 目标排名
					int newRanking = (int) keyWordInfo.get("new_ranking");
					int reachDays = 0;
					Integer importNewRanking = Integer.parseInt(keyWord.getNewRanking()); // 导入的最新排名
					Map<String, Object> dataSorting = DataSorting(keyWord); // 数据整理
					if (targetRanking >= importNewRanking && targetRanking < newRanking) {
						reachDays = 1;
					} else if (targetRanking >= newRanking && targetRanking < importNewRanking) {
						reachDays = -1;
					}

					if (targetRanking >= importNewRanking) { // 如果目标排名大于等于
						dataSorting.put("isTarget", "01"); // 达标
						keyWordInfo.put("is_target", "01"); // 达标
					} else {
						dataSorting.put("isTarget", "00"); // 未达标
						keyWordInfo.put("is_target", "00"); // 未达标
					}
					dataSorting.put("keyWordId", keyWordId);

					if (initRanking == -1) { // 只有 初排 为-1的时候 才更新初排 否则就不更新
						dataSorting.put("initRanking", keyWord.getNewRanking());// 初排
					}
					if (StringUtils.isEmpty(runTime)) {
						dataSorting.put("importTime", importTime);
						// 更新主表数据
						int primaryNum = newStationMapper.updateKeyword(dataSorting);
						// 新站 没有代理副表
//						if (primaryNum > 0) {
//							// 更新主表数据 更新主表完毕 在进行 代理表的更新
//							// proxyKeyWordInfo是否有这条数据 有就更新 代理表 没有 跳过
//							// 根据主表的id 查询代理表
//							proxyKeyWordInfo = keywordGMapper.getProxyByKeyWordId(keyWordId);
//							if (proxyKeyWordInfo != null && proxyKeyWordInfo.size() > 0) { // 更新代理表数据
//								keywordGMapper.updateProxyKeyword(dataSorting);
//							}
//						}
						// 此处赋值 是为啦下面进行修改昨日排名准备的
						runTime = importTime;
					} else {
						// importTime 时间 和主表中的 run_time时间做比较 如果t为true 则说明
						// importTime>=run_time 更新数据 否则跳过
						boolean t = DateUtil.compareDate(importTime, runTime);
						if (t) { // t为true 则说明 importTime>=run_time 更新数据 否则跳过
							dataSorting.put("importTime", importTime);
							// 更新主表数据
							int primaryNum = newStationMapper.updateKeyword(dataSorting);
							// 新站没有代理子表
//							if (primaryNum > 0) {
//								// 更新主表数据 更新主表完毕 在进行 代理表的更新
//								// proxyKeyWordInfo是否有这条数据 有就更新 代理表 没有 跳过
//								// 根据主表的id 查询代理表
//								proxyKeyWordInfo = keywordGMapper.getProxyByKeyWordId(keyWordId);
//								if (proxyKeyWordInfo != null && proxyKeyWordInfo.size() > 0) { // 更新代理表数据
//									keywordGMapper.updateProxyKeyword(dataSorting);
//								}
//							}
							// 此处赋值 是为啦下面进行修改昨日排名准备的
							runTime = importTime;
						}

					}
					String target = (String) keyWordInfo.get("is_target");
					// 根据主表中的id 以及 前台传入的runtime时间
					// 在seo_new_keywords_user_detail进行查询详情
					Map<String, Object> pamDetail = new HashMap<>();
					pamDetail.put("keyWordId", keyWordId);
					pamDetail.put("importTime", importTime);
					Map<String, Object> keywordsUserDetailInfo = newStationMapper
							.getInfoByKeyWordIdAndRuntime(pamDetail);
					// 如果 有值 就更新数据 否则 添加数据
					if (keywordsUserDetailInfo != null) {
						// 明细表中的达标字段 如果is_target=01 说明已经达标 那么说明今天的达标天数字段已经更新过一次
						dataSorting.put("importTime", importTime);
						if (reachDays != 0) {
							// 如果关键词明细表中添加数据 并且 这条excl数据 也达标啦 那么就在主表中 更改达标天数+1
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("reachDays", reachDays);
							newStationMapper.updateKeyword(reachMap);

						}
						dataSorting.put("reachDays", reachDays < 0 ? 0 : reachDays);
						dataSorting.put("price", keyWordInfo.get("price"));
						newStationMapper.updateKeywordDetail(dataSorting);
					} else {
						// keyWordInfo 主表查询结果 proxyKeyWordInfo代理表查询的结果
						// importTime前台传的时间 keyWord excel文档的数据
						Map<String, Object> detailMap = keywordsUserDetailSorting(keyWordInfo, null, importTime,
								keyWord);
						newStationMapper.addKeywordsUserDetail(detailMap);
						// 添加的时候 明细表中不可能有达标数据 都是主表中的数据 主表已经达标 那么就要在主表中的达标天数 +1
						// 否则不更新
						if ("01".equals(target)) {
							// 如果关键词明细表中添加数据 并且 这条excl数据 也达标啦 那么就在主表中 更改达标天数 +1
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("reachDays", 1);
							newStationMapper.updateKeyword(reachMap);
						}
					}
					Map<String, Object> afterDetail = new HashMap<>();
					// 修改昨日排名
					String afterDate = DateUtil.getAfterDayDate(runTime, -1, 1);
					afterDetail.put("keyWordId", keyWordId);
					afterDetail.put("importTime", afterDate);
					// 查询出来昨天的 明细数据 然后进行判断 最新排名 如果最新排名为 -1 则不做任何修改 如果不是-1
					// 把主表的昨日排名 修改为 明细中的最新排名
					Map<String, Object> afterKeywordsUserDetailInfo = newStationMapper
							.getInfoByKeyWordIdAndRuntime(afterDetail);
					if (afterKeywordsUserDetailInfo != null) {
						int ydayRanking = (int) afterKeywordsUserDetailInfo.get("new_ranking");
						if (ydayRanking != -1) {
							Map<String, Object> reachMap = new HashMap<>();
							reachMap.put("keyWordId", keyWordId);
							reachMap.put("ydayRanking", ydayRanking);
							newStationMapper.updateKeyword(reachMap);
						}
					}
				} else {
					errNum += 1;
					keyWordError.add("第" + (i + 2) + "行关键词数据库没有");
				}

			} catch (Exception e) {
				log.error("第" + (i + 2) + "行导入失败[{}]", e);
				keyWordError.add("第" + (i + 2) + "行导入失败");
			}
		}
		rb.put("keyWordError", keyWordError);
		rb.put("errNum", errNum);
		log.info("\r<br>插入数据库耗时 : " + (System.currentTimeMillis() - b) / 1000f + " 秒 ");
		return rb.success();
	}

	/**
	 * 修改数据整理
	 * 
	 * @return
	 */
	public Map<String, Object> DataSorting(KeyWord keyWord) {
		Map<String, Object> pam = new HashMap<>();
		pam.put("keyWordName", keyWord.getName());// 关键词
		pam.put("domain", keyWord.getDomain());// 域名
		pam.put("keyWordIndex", keyWord.getKeywordIndex());// 关键词指数
		pam.put("engineCode", keyWord.getEngineCode());// 关键词引擎
		pam.put("newRanking", keyWord.getNewRanking());// 新排
		pam.put("isInclude", keyWord.getIsInclude());// 是否收录
		return pam;
	}

	/**
	 * 整理明细表数据
	 * 
	 * @param keyWord
	 * @return
	 */
	public Map<String, Object> keywordsUserDetailSorting(Map<String, Object> primaryMap, Map<String, Object> proxyMap,
			String importTime, KeyWord keyWord) {
		Map<String, Object> pam = new HashMap<>();
		pam.put("run_time", importTime); // 执行时间
		pam.put("keywords_id", primaryMap.get("id")); // 主表id
		pam.put("name", keyWord.getName()); // 关键词
		pam.put("user_id", primaryMap.get("user_id")); // 用户id
		pam.put("real_user_id", primaryMap.get("real_user_id")); // 用户id
		pam.put("engine_code", keyWord.getEngineCode()); // 引擎
		pam.put("price", primaryMap.get("price")); // 主表价格
		pam.put("domain", keyWord.getDomain()); // 域名
		pam.put("keyword_index", keyWord.getKeywordIndex()); // 指标
		pam.put("target_ranking", primaryMap.get("target_ranking")); // 目标排名
		pam.put("new_ranking", keyWord.getNewRanking()); // 最新排名
		pam.put("is_target", primaryMap.get("is_target")); // 是否达标
		String isTarget = (String) primaryMap.get("is_target");
		if ("01".equals(isTarget)) {
			pam.put("reach_days", 1);
		} else {
			pam.put("reach_days", 0);
		}
		pam.put("is_include", primaryMap.get("is_include")); // 是否收录
		pam.put("remark", primaryMap.get("remark")); // 备注
		pam.put("create_time", DateUtil.getTime()); // 创建时间
		pam.put("update_time", DateUtil.getTime()); // 修改时间
		pam.put("create_id", primaryMap.get("create_id")); // 创建人
		pam.put("update_id", primaryMap.get("update_id")); // 修改人
		if (proxyMap != null && proxyMap.size() > 0) {
			pam.put("proxy_user_id", proxyMap.get("proxy_user_id")); // 代理id
			pam.put("price_1", proxyMap.get("price")); // 代理表价格
		}
		return pam;
	}

	/**
	 * 判断导入的excel是哪种类型的excel
	 * 
	 * @param sheet
	 * @return String res 返回结果为00 代表没有识别到规定的excel 01 厂商导入excel 02 搜索引擎排名excel
	 */
	public String checkTitle(Sheet sheet) {
		// 获取excel第一行的 title数据
		Row title = sheet.getRow(0);
		log.info("获取title：" + title);
		String oneName = title.getCell(0).getStringCellValue(); // 第一列
		String twoName = title.getCell(1).getStringCellValue(); // 第二列
		String threeName = title.getCell(2).getStringCellValue(); // 第三列
		String foutName = title.getCell(3).getStringCellValue(); // 第四列
		String fiveName = title.getCell(4).getStringCellValue(); // 第五列
		String sixName = title.getCell(5).getStringCellValue(); // 第六列
		String sevenName = title.getCell(6).getStringCellValue(); // 第七列
		String res = "00"; // 返回结果为00 代表没有识别到规定的excel 01 厂商导入excel 02
							// 搜索引擎排名excel
		if ("关键词".equals(oneName) && "域名".equals(twoName) && "指数".equals(threeName) && "类型".equals(foutName)
				&& "初排".equals(fiveName) && "新排".equals(sixName) && "创建日期".equals(sevenName)) {
			res = "01";
		} else if ("序号".equals(oneName) && "关键词".equals(twoName) && "网址".equals(threeName) && "搜索引擎".equals(foutName)
				&& "收录".equals(fiveName) && "排名".equals(sixName) && "名称".equals(sevenName)) {
			res = "02";
		} else {
			res = "00";
		}
		return res;

	}

	/**
	 * 厂商导入
	 * 
	 * @param sheet sheet
	 * @return ReturnBody rb
	 */
	public ReturnBody venderImport(Sheet sheet) {
		ReturnBody rb = ReturnBody.init();
		List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
		List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
		List<Map<String, Object>> engineList = newStationMapper.getEngineList();
		KeyWord keyWord;
		int importNum = 0; // 记录一共导入多少条数据
		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
			StringBuffer resBu = new StringBuffer();
			if (resBu.length() > 0) {
				resBu.delete(0, resBu.length() - 1);
			}
			try {
				Row row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				keyWord = new KeyWord();
				String name = null;
				String domain = null;
				String domainStr = null;
				String keyWordIndex = null;
				String engine = null;
				String initRanking = null;
				String newRanking = null;
				// 关键词
				if (row.getCell(0) != null) {
					name = row.getCell(0).getStringCellValue();
					if (name == null || name.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
				}

				// 域名
				if (row.getCell(1) != null) {
					domain = row.getCell(1).getStringCellValue();
					if (domain == null || domain.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
					}
					domainStr = domain.replaceFirst("(https?://)", "");
				} else {
					log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
				}

				// 指数
				if (row.getCell(2) != null) {
					row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
					keyWordIndex = row.getCell(2).getStringCellValue();
				}

				if (row.getCell(3) != null) {
					// 搜索引擎
					engine = row.getCell(3).getStringCellValue();
					if (engine == null || engine.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
				}

				if (row.getCell(4) != null) {
					// 初排名
					row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
					initRanking = row.getCell(4).getStringCellValue();
				}
				if (row.getCell(5) != null) {
					// 新排名
					row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
					newRanking = row.getCell(5).getStringCellValue();
					if (newRanking == null || newRanking.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
				}
				keyWord.setName(name); // 关键词
				keyWord.setDomain(domainStr); // 域名
				keyWord.setKeywordIndex(keyWordIndex); // 指数
				if (StringUtils.isNotBlank(engine)) {
					for (int i = 0; i < engineList.size(); i++) {
						Map<String, Object> engineMap = engineList.get(i);
						String engineStr = (String) engineMap.get("fuzzy");
						String code = (String) engineMap.get("code");
						boolean boo = engineStr.contains(engine);
						if (boo) {
							keyWord.setEngineCode(code);// 搜索引擎
							break;
						}

					}
				} else {
					keyWord.setEngineCode(null);// 搜索引擎
				}
				keyWord.setInitRanking(initRanking); // 初排
				if ("100+".equals(newRanking) || "-".equals(newRanking)) {
					keyWord.setNewRanking("10000");
				} else {
					keyWord.setNewRanking(newRanking);
				}

				if (!CommonUtil.isNumeric(keyWord.getNewRanking())) {
					log.error("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
					resBu.append("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
				}

				importNum += 1;
				keyWordSucessList.add(keyWord);
				if (resBu != null && resBu.length() > 0) {
					keyWordErrorList.add(resBu);
				}
			} catch (Exception e) {
				resBu.append("导入失败(第" + (r + 1) + "行,数据异常)");
				keyWordErrorList.add(resBu);
			}

		}
		rb.put("importNum", importNum);
		rb.put("keyWordSucessList", keyWordSucessList);
		rb.put("keyWordErrorList", keyWordErrorList);
		if (!keyWordErrorList.isEmpty()) {
			return rb.rollback();
		}

		return rb.success();
	}

	/**
	 * 查询导入
	 * 
	 * @param sheet sheet
	 * @return ReturnBody rb
	 */
	public ReturnBody engineImport(Sheet sheet) {
		ReturnBody rb = ReturnBody.init();
		List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
		List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
		List<Map<String, Object>> engineList = newStationMapper.getEngineList();
		KeyWord keyWord;
		int importNum = 0; // 记录一共导入多少条数据

		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
			StringBuffer resBu = new StringBuffer();
			if (resBu.length() > 0) {
				resBu.delete(0, resBu.length() - 1);
			}
			try {
				Row row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				keyWord = new KeyWord();
				String name = null;
				String domain = null;
				String domainStr = null;
				String engine = null;
				// String isInclude = null;
				String newRanking = null;
				// 关键词
				if (row.getCell(1) != null) {
					name = row.getCell(1).getStringCellValue();
					if (name == null || name.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,关键字未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,关键字未填写)");
				}
				if (row.getCell(2) != null) {
					// 域名
					domain = row.getCell(2).getStringCellValue();
					if (domain == null || domain.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
					}
					domainStr = domain.replaceFirst("(https?://)", "");
				} else {
					log.error("导入失败(第" + (r + 1) + "行,域名未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,域名未填写)");
				}
				if (row.getCell(3) != null) {
					// 搜索引擎
					engine = row.getCell(3).getStringCellValue();
					if (engine == null || engine.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,搜索引擎未填写)");
				}
				// if(row.getCell(4)!=null){
				// // 收录
				// row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
				// isInclude = row.getCell(4).getStringCellValue();
				// if (isInclude == null || isInclude.isEmpty()) {
				// log.error("导入失败(第" + (r + 1) + "行,收录未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,收录未填写)");
				// }
				// }else{
				// log.error("导入失败(第" + (r + 1) + "行,收录未填写)");
				// resBu.append("导入失败(第" + (r + 1) + "行,收录未填写)");
				// }
				if (row.getCell(5) != null) {
					// 排名
					row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
					newRanking = row.getCell(5).getStringCellValue();
					if (newRanking == null || newRanking.isEmpty()) {
						log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
						resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
					}
				} else {
					log.error("导入失败(第" + (r + 1) + "行,新排未填写)");
					resBu.append("导入失败(第" + (r + 1) + "行,新排未填写)");
				}
				keyWord.setName(name); // 关键词
				keyWord.setDomain(domainStr); // 域名
				if (StringUtils.isNotBlank(engine)) {
					for (int i = 0; i < engineList.size(); i++) {
						Map<String, Object> engineMap = engineList.get(i);
						String engineStr = (String) engineMap.get("fuzzy");
						String code = (String) engineMap.get("code");
						boolean boo = engineStr.contains(engine);
						if (boo) {
							keyWord.setEngineCode(code);// 搜索引擎
							break;
						}

					}
				} else {
					keyWord.setEngineCode(null);// 搜索引擎
				}

				if ("100+".equals(newRanking) || "-".equals(newRanking)) {
					keyWord.setNewRanking("10000");
				} else {
					keyWord.setNewRanking(newRanking);
				}
				if (!CommonUtil.isNumeric(keyWord.getNewRanking())) {
					log.error("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
					resBu.append("导入失败(第" + (r + 1) + "行,最新排名不是数字)");
				}

				importNum += 1;
				keyWordSucessList.add(keyWord);
				if (resBu != null && resBu.length() > 0) {
					keyWordErrorList.add(resBu);
				}
			} catch (Exception e) {
				resBu.append("导入失败(第" + (r + 1) + "行,异常)");
				keyWordErrorList.add(resBu);
			}
		}
		rb.put("importNum", importNum);
		rb.put("keyWordSucessList", keyWordSucessList);
		rb.put("keyWordErrorList", keyWordErrorList);
		if (!keyWordErrorList.isEmpty()) {
			return rb.rollback();
		}
		return rb.success();
	}

	/**
	 * 根据关键词id查询详情
	 */
	public Map<String, Object> getInfoBykeywordId(Map<String, Object> pam) {
		return newStationMapper.getInfoBykeywordId(pam);
	}

	/**
	 * 修改最新排名
	 */
	public ReturnBody updateNewRanking(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
			List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
			KeyWord keyWord = new KeyWord();
			;
			StringBuffer resBu = new StringBuffer();
			if (pam != null) {
				String name = (String) pam.get("name");
				String domain = (String) pam.get("domain");
				String engine_code = (String) pam.get("engine_code");
				String newRanking = (String) pam.get("newRanking");
				if (StringUtils.isNotEmpty(name)) {
					keyWord.setName(name); // 关键词
				} else {
					resBu.append("传入关键字为空");
				}
				if (StringUtils.isNotEmpty(domain)) {
					keyWord.setDomain(domain); // 域名
				} else {
					resBu.append("传入域名为空");
				}
				if (StringUtils.isNotEmpty(engine_code)) {
					keyWord.setEngineCode(engine_code);// 搜索引擎
				} else {
					resBu.append("传入搜索引擎为空");
				}
				if (StringUtils.isNotEmpty(newRanking)) {
					keyWord.setNewRanking(newRanking.toString()); // 新排
				} else {
					resBu.append("传入最新排名为空");
				}
			} else {
				resBu.append("传入的map对象为空");
			}
			keyWordSucessList.add(keyWord);
			if (resBu != null && resBu.length() > 0) {
				keyWordErrorList.add(resBu);
			}
			rb.put("keyWordSucessList", keyWordSucessList);
			rb.put("keyWordErrorList", keyWordErrorList);
			if (!keyWordErrorList.isEmpty()) {
				return rb.rollback();
			}
			String importime = DateUtil.yMdToYmdmds(DateUtil.getDay());
			rb = importDataToDataBase(rb, importime);
			return rb;
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	/**
	 * 修改昨日排名 只是把importime时间调成昨天即可
	 */
	public ReturnBody updateYesRanking(Map<String, Object> pam) {
		ReturnBody rb = ReturnBody.init();
		try {
			List<KeyWord> keyWordSucessList = new ArrayList<KeyWord>();
			List<StringBuffer> keyWordErrorList = new ArrayList<StringBuffer>();
			KeyWord keyWord = new KeyWord();
			StringBuffer resBu = new StringBuffer();
			String runTime = null;
			if (pam != null) {
				String name = (String) pam.get("name");
				String domain = (String) pam.get("domain");
				String engine_code = (String) pam.get("engine_code");
				String newRanking = (String) pam.get("newRanking");
				runTime = (String) pam.get("run_time");
				if (StringUtils.isNotEmpty(name)) {
					keyWord.setName(name); // 关键词
				} else {
					resBu.append("传入关键字为空");
				}
				if (StringUtils.isNotEmpty(domain)) {
					keyWord.setDomain(domain); // 域名
				} else {
					resBu.append("传入域名为空");
				}
				if (StringUtils.isNotEmpty(engine_code)) {
					keyWord.setEngineCode(engine_code);// 搜索引擎
				} else {
					resBu.append("传入搜索引擎为空");
				}
				if (StringUtils.isNotEmpty(newRanking)) {
					keyWord.setNewRanking(newRanking); // 新排
				} else {
					resBu.append("传入最新排名为空");
				}
			} else {
				resBu.append("传入的map对象为空");
			}
			keyWordSucessList.add(keyWord);
			if (resBu != null && resBu.length() > 0) {
				keyWordErrorList.add(resBu);
			}
			rb.put("keyWordSucessList", keyWordSucessList);
			rb.put("keyWordErrorList", keyWordErrorList);
			if (!keyWordErrorList.isEmpty()) {
				return rb.rollback();
			}
			// 时间为昨天
			String importime = DateUtil.yMdToYmdmds(DateUtil.getAfterDayDate(runTime, -1, -1));
			rb = importDataToDataBase(rb, importime);
			return rb;
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	@Override
	public List<Map<String, Object>> getRecycleBinList(Map<String, Object> params) {
		return newStationMapper.getRecycleBinList(params);
	}

	@Override
	public int keyWordUpdate(Map<String, Object> pam) {
		return newStationMapper.updateKeyWordD(pam);
	}

	@Override
	public int deleteK(Map<String, Object> pam) {
		newStationMapper.deletek(pam);
		newStationMapper.deleteKeyWordR(pam);
		return 1;
	}

}